#!/bin/bash

# Web Notes 应用一键部署脚本 - Ubuntu 24.04
# 用法: ./deploy-ubuntu.sh

set -e  # 遇到错误立即退出

echo "🚀 开始部署 Web Notes 应用 (Ubuntu 24.04)..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置变量
APP_DIR="/var/www/web-notes"
BACKEND_DIR="$APP_DIR/web-notes-backend"
FRONTEND_DIR="$APP_DIR/web-notes-frontend"
NGINX_CONFIG="/etc/nginx/sites-available/web-notes"
NGINX_ENABLED="/etc/nginx/sites-enabled/web-notes"
PM2_CONFIG="$APP_DIR/ecosystem.config.json"

# 检查是否为 root 用户
check_root() {
    if [[ $EUID -eq 0 ]]; then
        echo -e "${RED}请不要使用 root 用户运行此脚本${NC}"
        exit 1
    fi
}

# 检查系统
check_system() {
    echo -e "${YELLOW}检查系统环境...${NC}"
    
    if ! command -v node &> /dev/null; then
        echo -e "${RED}Node.js 未安装，请先运行 install-dependencies-ubuntu.sh${NC}"
        exit 1
    fi
    
    if ! command -v npm &> /dev/null; then
        echo -e "${RED}npm 未安装${NC}"
        exit 1
    fi
    
    if ! command -v nginx &> /dev/null; then
        echo -e "${RED}Nginx 未安装${NC}"
        exit 1
    fi
    
    if ! command -v pm2 &> /dev/null; then
        echo -e "${RED}PM2 未安装，正在安装...${NC}"
        sudo npm install -g pm2
    fi
    
    if ! systemctl is-active --quiet mongod; then
        echo -e "${RED}MongoDB 未运行，请启动 MongoDB${NC}"
        echo -e "${YELLOW}尝试启动: sudo systemctl start mongod${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}系统环境检查通过${NC}"
}

# 创建目录结构
create_directories() {
    echo -e "${YELLOW}创建目录结构...${NC}"
    
    sudo mkdir -p $APP_DIR
    sudo chown $USER:$USER $APP_DIR
    mkdir -p $APP_DIR/logs
}

# 安装后端
install_backend() {
    echo -e "${YELLOW}安装后端应用...${NC}"
    
    cd $BACKEND_DIR
    
    # 先安装所有依赖 (包括 devDependencies 用于构建)
    npm install
    
    # 构建应用
    npm run build
    
    # 构建完成后清理 devDependencies (可选，节省空间)
    # npm prune --production
    
    # 创建环境配置
    if [ ! -f .env ]; then
        cp .env.production .env
        echo -e "${YELLOW}请编辑 $BACKEND_DIR/.env 文件配置生产环境参数${NC}"
    fi
    
    # 创建上传目录
    mkdir -p uploads/images
    
    echo -e "${GREEN}后端安装完成${NC}"
}

# 构建前端
build_frontend() {
    echo -e "${YELLOW}构建前端应用...${NC}"
    
    cd $FRONTEND_DIR
    
    # 安装依赖
    npm install
    
    # 构建生产版本
    npm run build
    
    echo -e "${GREEN}前端构建完成${NC}"
}

# 配置 Nginx
configure_nginx() {
    echo -e "${YELLOW}配置 Nginx...${NC}"
    
    # 创建 Nginx 配置
    sudo tee $NGINX_CONFIG > /dev/null << 'EOF'
server {
    listen 80;
    server_name _;  # 替换为你的域名或保持 _ 使用IP访问
    
    # 日志配置
    access_log /var/log/nginx/web-notes-access.log;
    error_log /var/log/nginx/web-notes-error.log;
    
    # 静态文件服务 (前端)
    location / {
        root /var/www/web-notes/web-notes-frontend/dist;
        try_files $uri $uri/ /index.html;
        
        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }
    
    # API 代理到后端
    location /api/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        
        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
    
    # 上传文件服务
    location /uploads/ {
        alias /var/www/web-notes/web-notes-backend/uploads/;
        expires 1y;
        add_header Cache-Control "public";
        
        # 安全设置
        location ~* \.(php|jsp|cgi|asp|aspx)$ {
            deny all;
        }
    }
    
    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
    
    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    
    # 文件上传大小限制
    client_max_body_size 10M;
}
EOF
    
    # 启用站点
    sudo ln -sf $NGINX_CONFIG $NGINX_ENABLED
    
    # 移除默认配置
    sudo rm -f /etc/nginx/sites-enabled/default
    
    # 测试配置
    sudo nginx -t
    
    # 重启 Nginx
    sudo systemctl restart nginx
    
    echo -e "${GREEN}Nginx 配置完成${NC}"
}

# 配置 PM2
configure_pm2() {
    echo -e "${YELLOW}配置 PM2...${NC}"
    
    # 停止可能存在的进程
    pm2 delete web-notes-api 2>/dev/null || true
    
    # 创建 PM2 配置文件
    tee $PM2_CONFIG > /dev/null << EOF
{
  "name": "web-notes-api",
  "script": "dist/index.js",
  "cwd": "$BACKEND_DIR",
  "instances": 1,
  "exec_mode": "fork",
  "env": {
    "NODE_ENV": "production",
    "PORT": 3000
  },
  "log_file": "$APP_DIR/logs/web-notes-api.log",
  "out_file": "$APP_DIR/logs/web-notes-api-out.log",
  "error_file": "$APP_DIR/logs/web-notes-api-error.log",
  "log_date_format": "YYYY-MM-DD HH:mm:ss Z",
  "merge_logs": true,
  "max_restarts": 10,
  "min_uptime": "10s",
  "max_memory_restart": "500M",
  "restart_delay": 4000,
  "autorestart": true,
  "watch": false
}
EOF
    
    # 启动应用
    pm2 start $PM2_CONFIG
    
    # 保存 PM2 配置
    pm2 save
    
    echo -e "${GREEN}PM2 配置完成${NC}"
}

# 设置权限
set_permissions() {
    echo -e "${YELLOW}设置文件权限...${NC}"
    
    # 设置应用目录权限
    sudo chown -R $USER:$USER $APP_DIR
    chmod -R 755 $APP_DIR
    
    # 设置上传目录权限
    chmod -R 755 $BACKEND_DIR/uploads
    
    echo -e "${GREEN}权限设置完成${NC}"
}

# 检查服务状态
check_services() {
    echo -e "${YELLOW}检查服务状态...${NC}"
    
    echo -e "\n=== MongoDB 状态 ==="
    sudo systemctl status mongod --no-pager -l || echo -e "${RED}MongoDB 状态异常${NC}"
    
    echo -e "\n=== Nginx 状态 ==="
    sudo systemctl status nginx --no-pager -l || echo -e "${RED}Nginx 状态异常${NC}"
    
    echo -e "\n=== PM2 应用状态 ==="
    pm2 status || echo -e "${RED}PM2 状态异常${NC}"
    
    echo -e "\n=== 应用日志 (最近10行) ==="
    pm2 logs web-notes-api --lines 10 --nostream || echo -e "${RED}无法获取应用日志${NC}"
    
    echo -e "\n=== 端口监听状态 ==="
    sudo ss -tulnp | grep -E ':(80|443|3000|27017)' || echo -e "${YELLOW}未找到预期端口${NC}"
}

# 测试应用
test_application() {
    echo -e "${YELLOW}测试应用连接...${NC}"
    
    # 等待服务启动
    sleep 3
    
    # 测试后端 API
    if curl -s http://localhost:3000/health > /dev/null; then
        echo -e "${GREEN}✓ 后端 API 响应正常${NC}"
    else
        echo -e "${RED}✗ 后端 API 无响应${NC}"
    fi
    
    # 测试前端页面
    if curl -s http://localhost/ > /dev/null; then
        echo -e "${GREEN}✓ 前端页面可访问${NC}"
    else
        echo -e "${RED}✗ 前端页面无法访问${NC}"
    fi
}

# 显示完成信息
show_completion_info() {
    SERVER_IP=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')
    
    echo -e "\n${GREEN}🎉 Ubuntu 24.04 部署完成!${NC}"
    echo -e "\n=== 访问信息 ==="
    echo -e "应用地址: ${GREEN}http://$SERVER_IP${NC}"
    echo -e "API 地址: ${GREEN}http://$SERVER_IP/api${NC}"
    
    echo -e "\n=== 常用命令 ==="
    echo -e "查看应用状态: ${YELLOW}pm2 status${NC}"
    echo -e "查看应用日志: ${YELLOW}pm2 logs web-notes-api${NC}"
    echo -e "重启应用: ${YELLOW}pm2 restart web-notes-api${NC}"
    echo -e "重启 Nginx: ${YELLOW}sudo systemctl restart nginx${NC}"
    echo -e "查看系统日志: ${YELLOW}sudo journalctl -f${NC}"
    
    echo -e "\n=== 配置文件位置 ==="
    echo -e "后端环境配置: ${YELLOW}$BACKEND_DIR/.env${NC}"
    echo -e "Nginx 配置: ${YELLOW}$NGINX_CONFIG${NC}"
    echo -e "PM2 配置: ${YELLOW}$PM2_CONFIG${NC}"
    echo -e "应用日志: ${YELLOW}$APP_DIR/logs/${NC}"
    
    echo -e "\n=== 下一步操作 ==="
    echo -e "1. 编辑 ${YELLOW}$BACKEND_DIR/.env${NC} 配置数据库连接和 JWT 密钥"
    echo -e "2. 如果使用域名，更新 Nginx 配置中的 server_name"
    echo -e "3. 配置 SSL 证书: ${YELLOW}sudo certbot --nginx -d yourdomain.com${NC}"
    echo -e "4. 设置定期备份: ${YELLOW}crontab -e${NC}"
    
    echo -e "\n=== 安全提醒 ==="
    echo -e "1. 修改默认的 JWT 密钥"
    echo -e "2. 配置 MongoDB 认证 (推荐)"
    echo -e "3. 定期更新系统: ${YELLOW}sudo apt update && sudo apt upgrade${NC}"
    echo -e "4. 监控日志和系统资源"
}

# 主函数
main() {
    check_root
    check_system
    create_directories
    install_backend
    build_frontend
    configure_nginx
    configure_pm2
    set_permissions
    check_services
    test_application
    show_completion_info
}

# 运行主函数
main "$@"